package com.frost.book.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.frost.book.model.Result;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 对哪些请求进行统一结果返回处理, true-对请求进行处理 false-对请求不进行处理
        return true;
    }

    /**
     * 对返回结果进行统一结果返回处理
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 结果为 Result 直接返回
        if (body instanceof Result) {
            return body;
        }
        // 结果为 String 类型在返回之前进行处理类型不匹配问题
        if (body instanceof String) {
//            return Result.success(body); // 类型不匹配
            String s = objectMapper.writeValueAsString(Result.success(body));
            return s;
        }
        // 对返回结果进行统一结果返回处理
        return Result.success(body);
    }
}
